import Toast from 'tdesign-miniprogram/toast/index';
import Log from '../../utils/log';
import commondUtil from '../../utils/commondUtil';
import SignRecord from "../../api/modules/signRecord";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    clientInfo: {},
    signRecordList: [],
    pageParam: {
      page: 1,
      pageSize: 30,
      total: 0,
    },
    allPages: 1,
    refreshDataTask: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel();
    if (typeof eventChannel?.on === 'function') {
      // 监听'delivery'事件，并获取数据包
      eventChannel.on('delivery', (param) => {
        const clientInfo = param?.clientInfo;
        if (clientInfo == null) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '客户端信息为空！',
            theme: 'error',
            direction: 'column',
          });
          wx.navigateBack();
          return;
        }
        this.setData({
          clientInfo: clientInfo
        });
        this.getClientSignRecord(true);
      });
    }
  },

  onUnload() {
    if (this.data.refreshDataTask != null) {
      clearTimeout(this.data.refreshDataTask == null);
    }
  },

  getClientSignRecord(initFlag) {
    if (this.data.refreshDataTask != null) {
      clearTimeout(this.data.refreshDataTask == null);
    }
    return new Promise((resolve) => {
      const clientId = this.data.clientInfo?.id;
      if (commondUtil.isBlank(clientId)) {
        resolve([]);
        return;
      }
      if (initFlag) {
        this.setData({
          pageParam: {
            page: 1,
            pageSize: 30,
            total: 0,
          }
        });
      }
      SignRecord.queryByCondition({
        clientId,
        ...this.data.pageParam
      }).then((resp) => {
        this.setData({
          enable: false
        });
        const rows = resp.data?.records
        if (commondUtil.isEmpty(rows)) {
          resolve([]);
          return;
        }
        let list = JSON.parse(JSON.stringify(this.data.signRecordList));
        if (this.data.pageParam.page == 1) {
          list = rows;
        } else {
          rows.forEach(row => {
            if (!list.some(item => item.id === row.id)) {
              list.push(row);
            }
          });
          list.sort((a, b) => commondUtil.parserDate(b.createTime) - commondUtil.parserDate(a.createTime));
        }
        list.forEach(item => {
          if (item.statusCode == null) {
            // 签到记录创建时间 距离 当前时间 (分钟)
            const diffMs = Math.floor((new Date() - commondUtil.parserDate(item.createTime)) / 60000);
            if (diffMs < this.data.clientInfo?.config?.estimateExecMin) {
              // 小于 预计签到执行时间(分钟)，签到中
              item.statusCode = 3;
            } else {
              // 否则为签到超时
              item.statusCode = 2;
            }
          }

          item.createTime = commondUtil.formatDate(item.createTime, true, false);
          if (item.signTime != null) {
            item.signTime = commondUtil.formatDate(item.signTime, true, false);
          }

          switch (item.statusCode) {
            case 0:
              item.title = '签到失败';
              item.statusImage = '/static/images/sign_error.png';
              break;
            case 1:
              item.title = '签到时间：' + item.signTime;
              item.statusImage = '/static/images/sign_success.png';
              break;
            case 2:
              item.title = '签到超时';
              item.statusImage = '/static/images/sign_timeout.png';
              break;
            case 3:
              item.title = '正在签到中...';
              item.statusImage = '/static/images/sign_ing.png';
              break;
            default:
              break;
          }
        });
        this.setData({
          signRecordList: list,
          'pageParam.total': resp.data.total,
          allPages: resp.data.pages
        });
        const refreshTime = (this.data.clientInfo?.config?.estimateExecMin || 2) * 60000;
        // 若存在签到中数据，则定时刷新
        if (this.data.refreshDataTask == null && list.some(item => item.statusCode == 3) && !isNaN(refreshTime)) {
          const timeoutId = setTimeout(() => {
            this.getClientSignRecord().then(() => {
              this.setData({
                refreshDataTask: null
              });
            });
          }, refreshTime);
          this.setData({
            refreshDataTask: timeoutId
          });
        }
        resolve(list);
      });
    });
  },

  showSignDetail(e) {
    const signRecordObj = e.currentTarget.dataset.item;
    let signDetail = signRecordObj.detailInfo || [];
    if (commondUtil.isNotEmpty(signDetail)) {
      try {
        signDetail = JSON.parse(signDetail);
      } catch (e) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '签到详情数据异常！',
          theme: 'error',
          direction: 'column',
        });
        Log.errorAll("解析签到详情数据异常！detailInfo：", detailInfo, e);
        return;
      }
    } else if (signRecordObj.statusCode != 3) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '无签到详情信息',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }

    // 跳转到签到详情界面
    const param = {
      signDetail: signDetail
    }
    if (signRecordObj.statusCode == 3) {
      if (commondUtil.isBlank(this.data.clientInfo?.clientName)) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '客户端名称为空！',
          theme: 'warning',
          direction: 'column',
        });
        return;
      }
      param.pageClientName = `${this.data.clientInfo.clientName}-page-${signRecordObj.id}-wx-${commondUtil.uuid()}`;
    }
    wx.navigateTo({
      url: '/pages/signRecordDetail/signRecordDetail',
      success: (res) => {
        res.eventChannel.emit('delivery', param);
      },
      events: {
        refreshSignRecord: () => {
          this.getClientSignRecord(true);
        }
      }
    });
  },

  onRefresh() {
    this.setData({
      enable: true
    });
    this.getClientSignRecord(true);
  },

  onReachBottom() {
    if (this.data.pageParam.page > this.data.allPages) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '没有更多数据了',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    this.setData({
      'pageParam.page': this.data.pageParam.page + 1
    });
    this.getClientSignRecord(false);
  }
})